<template>
  <div class="container">
    <div id="map"></div>
  </div>
</template>
  
  <script>
import "mapbox-gl/dist/mapbox-gl.css";
import mapboxgl from "mapbox-gl"; // or "const mapboxgl = require('mapbox-gl');"
// 导入所需的库
import * as turf from "@turf/turf";
export default {
  name: "Vue2MapboxMapTemplate",
  data() {
    return {};
  },

  mounted() {
    this.initMap();
  },

  methods: {
    initMap() {
      mapboxgl.accessToken =
        "pk.eyJ1IjoiY3Vpaml5aW5nIiwiYSI6ImNsZ3QyZjY4ODAxbDEza3BkOTJqbTJvN3gifQ.Ldj9qAFzb5uzcLP-VtFB3A";
      const map = new mapboxgl.Map({
        container: "map", // container ID
        style: "mapbox://styles/cuijiying/cll09l2nz007w01picbmj3e1z", // style URL
        center: [118.79013542048335, 32.05775855185749], // starting position [lng, lat]
        // center: mapboxgl.MercatorCoordinate.fromLngLat([118.79013542048335,32.05775855185749]), // starting position [lng, lat]
        zoom: 5, // starting zoom
        projection: "mercator",
      });

      //
      map.on("click", (evt) => {
        console.log(evt.lngLat);
      });


      // 创建一个 Mapbox GL JS 的 GeoJSON 对象
      const geojson = {
        type: "Feature",
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [120, 30],
              [125, 32],
              [126, 33],
              [120, 30],
            ],
          ],
        },
        properties: {
          name: "My Polygon",
        },
      };

    //   let tp = turf.getGeom(geojson);
    //   console.log(tp);
    //   let coords = this.flattenArray(tp.coordinates).join(',')
    //   console.log(tp.type + "((" + coords + "))");

    const wkt = this.geometryToWKT(geojson.geometry);
    console.log(wkt); // 输出: POINT(1 2)


    },

    flattenArray(arr) {
      let result = [];

      for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
          result = result.concat(this.flattenArray(arr[i]));
        } else {
          result.push(arr[i]);
        }
      }

      return result;
    },
    // 将 Geometry 对象转换为 WKT 字符串
    geometryToWKT(geometry) {
    if (geometry.type === 'Point') {
        return `POINT(${geometry.coordinates[0]} ${geometry.coordinates[1]})`;
    } else if (geometry.type === 'LineString') {
        const points = geometry.coordinates.map(coord => coord.join(' ')).join(', ');
        return `LINESTRING(${points})`;
    } else if (geometry.type === 'Polygon') {
        const rings = geometry.coordinates.map(ring =>
        `(${ring.map(coord => coord.join(' ')).join(', ')})`
        ).join(', ');
        return `POLYGON(${rings})`;
    } else {
        return null; // 对于其他几何类型，可以根据需要进行扩展
    }
    }
  },
};
</script>
  
  <style></style>
  